package com.blogsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blogsystem.entity.Article;
import com.blogsystem.entity.Comment;
import com.blogsystem.entity.User;
import com.blogsystem.mapper.UserMapper;
import com.blogsystem.service.ArticleService;
import com.blogsystem.service.ClickCountService;
import com.blogsystem.service.CommentService;
import com.blogsystem.service.UserService;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);


    @Autowired
    private ArticleService articleService;

    @Autowired
    private CommentService commentService;
    @Autowired
    private ClickCountService clickCountService;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public List<Article> getArticlesByUserId(Integer userId) {
        logger.debug("查询用户 {} 的文章", userId);
        List<Article> articles = articleService.list(new QueryWrapper<Article>().eq("user_id", userId).orderByDesc("create_time"));
        logger.debug("找到 {} 篇文章", articles.size());
        return articles;
    }

    @Override
    public List<Comment> getCommentsByUserId(Integer userId) {
        logger.debug("查询用户 {} 的评论", userId);
        List<Comment> comments = commentService.list(new QueryWrapper<Comment>().eq("user_id", userId).orderByDesc("create_time"));
        logger.debug("找到 {} 条评论", comments.size());
        return comments;
    }

    @Override
    public Map<String, Object> getUserStatistics(Integer userId) {
        logger.debug("获取用户 {} 的统计信息", userId);
        Map<String, Object> statistics = new HashMap<>();

        // 文章总数

        int articleCount = Math.toIntExact(articleService.count(new QueryWrapper<Article>().eq("user_id", userId)));
        statistics.put("articleCount", articleCount);

        // 评论总数
        int commentCount = Math.toIntExact(commentService.count(new QueryWrapper<Comment>().eq("user_id", userId)));
        statistics.put("commentCount", commentCount);

        // 累计点击量
        int clickCount = 0;
        // 获取用户的累计点击量
        if (userId != null) {
            clickCount = (int) clickCountService.getUserTotalClicks(userId);
        }
        statistics.put("clickCount", clickCount);

        return statistics;
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username 用户名
     * @return 用户对象
     */
    public User findByUsername(String username) {
        return query().eq("username", username).one();
    }

    @Override
    public boolean updateAvatar(Integer userId, String avatar) {
        User user = new User();
        user.setUserId(userId);
        user.setAvatar(avatar);
        return updateById(user);
    }

    @Override
    public boolean checkPassword(Integer userId, String rawPassword) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return false;
        }
        return passwordEncoder.matches(rawPassword, user.getPassword());
    }

    @Override
    public boolean updatePassword(Integer userId, String newPassword) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return false;
        }
        user.setPassword(passwordEncoder.encode(newPassword));
        int rowsAffected = userMapper.updateById(user);
        return rowsAffected > 0;
    }

    // 如果有自定义方法，可以在这里添加具体实现
    public Map<String, Object> getUserData(Authentication authentication) {
        if (authentication != null) {
            String username = authentication.getName();
            User user = findByUsername(username);
            if (user != null) {
                Map<String, Object> userData = new HashMap<>();
                userData.put("username", user.getUsername());
                userData.put("avatar", user.getAvatar());
                userData.put("role", user.getRole());
                userData.put("stat", getUserStatistics(user.getUserId()));
                userData.put("draftArticles", getDraftArticles(user.getUserId()));
                userData.put("pendingArticles", getPendingArticles(user.getUserId()));
                userData.put("articles", getArticlesByUserId(user.getUserId()));
                return userData;
            }
        }
        return null;
    }

    public List<Article> getDraftArticles(Integer userId) {
        logger.debug("查询用户 {} 的草稿文章", userId);
        List<Article> draftArticles = articleService.list(new QueryWrapper<Article>().eq("user_id", userId).eq("status", 0));
        logger.debug("找到 {} 篇草稿", draftArticles.size());
        return draftArticles;
    }
    public List<Article> getPendingArticles(Integer userId) {
        logger.debug("查询用户 {} 待审核文章", userId);
        List<Article> draftArticles = articleService.list(new QueryWrapper<Article>().eq("user_id", userId).eq("status", 2));
        logger.debug("找到 {} 篇待审核文章", draftArticles.size());
        return draftArticles;
    }

    public List<Article> getAllPendingArticles() {

        List<Article> pendingArticles = articleService.list(new QueryWrapper<Article>().eq("status", 2));

        logger.debug("找到 {} 篇待审核文章", pendingArticles.size());

        return pendingArticles;

    }


    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public Page<User> searchUsersByUsername(String keyword, int page, int limit) {
        Page<User> userPage = new Page<>(page, limit);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("username", keyword);
        return userMapper.selectPage(userPage, wrapper);
    }

    @Override
    public Page<User> list(int page, int limit) {
        Page<User> userPage = new Page<>(page, limit);
        return userMapper.selectPage(userPage, null);
    }
    // UserServiceImpl.java

public List<User> searchUsersByUsername(String username) {
    return userMapper.selectList(new QueryWrapper<User>().like("username", username));
}

    public int getAllPendingArticlesCount(){
        return (int) articleService.count(new QueryWrapper<Article>().eq("status", 2));
    }

}